<template>
  <div>
    <el-container>
      <el-aside width="280px">
        <div class="plr-4">
          <div class="app_card mb-2 pt-4  pb-4" style="height:calc(100vh - 200px);overflow-y: scroll;">
            <!--            <el-tree :data="dataOfGroups" node-key="id" :props="defaultProps" @node-click="onClickNode" />-->
            <el-tree :data="dataOfGroups" icon="CaretBottom" node-key="id" :props="defaultProps" @nodeClick="onClickNode">
              <template #default="{ node, data }">
                <span :class="{ 'is-active': data.id === selectedRoom.id && data.level === 2 }">{{ node.label }}</span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-aside>
      <el-main>
        <!-- <div class="app_card mb-2 pt-4 pb-4">
          <div class="d-flex justify-content-end align-items-center">
            <div>
              <el-button type="primary" @click="onAdd()">添加</el-button>
              <el-button type="primary" @click="onAdd()"><el-icon>
                  <Plus />
                </el-icon>批量编辑</el-button>
            </div>
          </div>
        </div> -->
        <div class="app_card pt-4  pb-5" v-if="selectedRoom.id">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-22">{{ selectedRoom.buildingName }}{{ selectedRoom.floorName }}-{{ selectedRoom.name }}
              </div>
              <div class="text-16 text-white-50 mt-3">
                排课教室：{{ selectedRoom.name }}
                排课日期：{{ baseDate().startOf('isoWeek').format("YYYY-MM-DD") }} 至 {{
                  baseDate().endOf('isoWeek').format("YYYY-MM-DD") }}
              </div>
            </div>
            <div class="search-form">
              <!--              <el-select v-model="semesterValue" style="width:200px" placeholder="请选择" class="mr-3">-->
              <!--                <el-option v-for="item in semesterOptions" :key="item.value" :label="item.label" :value="item.value" />-->
              <!--              </el-select>-->
              <!--              <el-select v-model="weekValue" style="width:100px" placeholder="请选择" class="mr-3">-->
              <!--                <el-option v-for="item in weekOptions" :key="item.value" :label="item.label" :value="item.value" />-->
              <!--              </el-select>-->
              <!--              <el-button type="primary" @click="onAdd()"><el-icon>-->
              <!--                  <Plus />-->
              <!--                </el-icon>批量编辑</el-button>-->
            </div>
          </div>
          <div style="height:calc(100vh - 320px);overflow-y: scroll;margin-top:40px">
            <div class="border-start  border-bottom  border-end clearfix rounded-4 text-truncate">
              <div class="position-relative clearfix bg-row">
                <div class="position-relative float-start  solid-top   t-c section-width duijiaoxian">
                  <div>节次</div>
                  <div>日期</div>
                </div>
                <div class="position-relative float-start solid-left solid-top   t-l week-width" v-for="k in 7">
                  <div class="text-14">{{ baseDate().startOf('isoWeek').add(k - 1, 'd').format("dddd") }}</div>
                  <div class="text-12 pt-2">{{ baseDate().startOf('isoWeek').add(k - 1, 'd').format("MM月DD日") }}</div>
                </div>
              </div>
              <div class=" position-relative clearfix" v-for="(item) of  lessonGroups">
                <div class="position-relative float-start  solid-top   t-c section-width bg-row">
                  <div class="fw-medium text-14">第{{ item.id }}节</div>
                </div>
                <!--                @click="handleRowClick(i)"-->
                <div class="position-relative float-start solid-left solid-top   t-l week-width"
                  v-for="weekItem of loadDataFormat(item.id)">
                  <div v-if="weekItem.id || weekItem.id">
                    <div class="text-16 fw-bolder">{{ weekItem.teacherName || '暂无老师' }}</div>
                    <div class="text-12 pt-2" style="white-space: normal">{{ weekItem.course }}</div>
                  </div>
                  <template v-else>
                    <div class="text-12 text-bs fw-medium t-c pt-3 position-relative">
                      <!--                      <el-icon>-->
                      <!--                        <Plus />-->
                      <!--                      </el-icon>新增-->
                      暂无
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
      <edit-dialog ref="editDialogRef" @success="loadData()"></edit-dialog>
    </el-container>
  </div>
</template>

<script setup>
/**
 * 教室管理
 */
import { ref, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';
import moment from "moment";
moment.locale('zh-cn', {
  weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
});
//组件
import EditDialog from './EditDialog.vue';

// ======================================================
//                      变量声明
// ======================================================
const roomId = 108



const baseDate = () => {
  return moment(semesterValue.value.startTime).add(queryParam.value.week - 1, 'week')
}

const authStore = useAuthStore();

// 组件引用
const editDialogRef = ref(null);

// 表格数据 不知道数据格式是什么暂时用以下格式
const weekCourse = ref([]);
// 表格数据
const dataOfGroups = ref([]);
const defaultProps = ref({
  label: 'name',
  children: 'list'
});
const dataOfTable = ref([]);

const semesterValue = ref('1')

const semesterOptions = [
  {
    value: '1',
    label: '2022年第一学期',
  },
  {
    value: '2',
    label: '2022年第二学期',
  },
  {
    value: '2',
    label: '2023年第一学期',
  },
  {
    value: '4',
    label: '2022年第二学期',
  },
]
const weekValue = ref('1')
const lessonGroups = ref([])
const selectedRoom = ref({})

// 表格查询参数
const queryParam = ref({ "sort": "Id", "order": "asc", "limit": 84, "query": "", roomId: null })

// ======================================================
//                      点击操作
// ======================================================



// ======================================================
//                      树形处理事件
// ======================================================


// 点击分组树形节点
const onClickNode = (data, a, b, c) => {
  console.log('点击树形节点', data, a, b, c)
  queryParam.value.roomId = data.id;
  if (data.level === 2) {
    selectedRoom.value = data
    loadData();
  }
}


const loadTreeData = () => {
  EsAjax.post(ApiUrls.buildingTree, {}).then(res => {
    console.error('res====', res)
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    ; (res.data.data || []).forEach((item) => {
      (item.list || []).forEach(_item => {
        (_item.list || []).forEach((__item) => {
          __item.level = 2
          __item.buildingName = item.name
          __item.floorName = _item.name
        })
      })
    });
    dataOfGroups.value = res.data.data
  }).catch(err => {
    ElMessage.error(err.message);
  })
}



// 点击刷新按钮
const onRefresh = () => {
  loadData();
}

// 点击新增按钮
const onAdd = (row = null) => {
  if (row) {
    editDialogRef.value.show(0, "添加" + row.title, row);
    return;
  }
  editDialogRef.value.show(0, "课表新增设置");
}





const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {

  if (rowIndex === 2) {
    if (columnIndex === 0) {
      return [1, 8]
    } else if (columnIndex === 1) {
      return [0, 0]
    }
  }
}





// 当某一行被点击时会触发该事件
const handleRowClick = (i) => {
  weekCourse.value[i].isChick = !weekCourse.value[i].isChick
  // editDialogRef.value.show(row.id, "课表编辑设置", [row]);
}

// ======================================================
//                      表格处理事件
// ======================================================

const loadData = () => {
  // const form = {"sort":"Id","order":"asc","limit":70,"query":"roomId=108"}
  const form = JSON.parse(JSON.stringify(queryParam.value))
  form.query = `roomId=${selectedRoom.value.id}`
  EsAjax.post(ApiUrls.timetableDatagrid, form).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    console.error('res.data.data===', res.data.data)
    dataOfTable.value = res.data.data.list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

const getLessonList = () => {
  EsAjax.post(ApiUrls.timetableconfigDatagrid, {
    "sort": "Id",
    "order": "asc",
    "limit": 12
  }
  ).then((res) => {
    lessonGroups.value = res.data.data.list || []
  })
}
const loadDataFormat = (idx) => {
  const _data = dataOfTable.value
  return [1, 2, 3, 4, 5, 6, 7].map((_item, _idx) => {
    console.log(_item);
    return _data.find(__item => __item.classIndex === idx && __item.weekday === _idx + 1) || {}
  })
}
onMounted(async () => {
  await getLessonList()
  await loadTreeData();
})

</script>
<style lang="less" scoped>
.section-width {
  width: 9%;
  height: 95px;
  line-height: 95px;
  box-sizing: border-box;
}

.duijiaoxian {
  background: linear-gradient(to top right,
      transparent 0%,
      transparent calc(50% - 1px),
      #474a6e 50%,
      transparent calc(50% + 1px),
      transparent 100%);

  >div:nth-of-type(1) {
    position: absolute;
    left: 33px;
    top: 15px;
  }

  >div:nth-of-type(2) {
    position: absolute;
    right: 34px;
    top: -18px;
  }
}

.week-width {
  width: 13%;
  height: 95px;
  box-sizing: border-box;
  padding: 15px;
}

.noon-width {
  width: 91%;
  box-sizing: border-box;
}

.noon-height {
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
}

.bg-row {
  background: #191d4a;
}

.is_chick {
  background: rgba(13, 184, 149, 0.14);
}
</style>

